package boundary;

import java.awt.GridBagLayout;
import javax.swing.JPanel;
import javax.swing.JLabel;
import store.BaseStore;
import store.Cibo;
import store.Termine;
import store.TuttiCibi;
import dataview.InfoCibo;
import dataview.Termini;
import dataview.TipoTermine;
import dataview.Unita;
import dataview.Valori;
import java.awt.GridBagConstraints;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.Insets;
import javax.swing.JButton;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.border.BevelBorder;
import javax.swing.JScrollPane;
import java.awt.Cursor;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;

public class ModificaInfoCibi extends JPanel implements ActionListener {
	
	private static final long serialVersionUID = 1L;
	private Home main;
	private String nomeCibo;
	private Cibo vecchioCibo = null;
	private Valori valori = null; //  @jve:decl-index=0:
	private Termini tag;
	private JLabel genereLabel = null;
	private JLabel descrLabel = null;
	private JLabel calorieLabel = null;
	private JTextField calorieField = null;
	private JLabel rifLabel = null;
	private JComboBox unitaBox = null;
	private JLabel valoriLabel = null;
	private JButton valoriButton = null;
	private JLabel jLabel = null;
	private JButton creaButton = null;
	private JScrollPane jScrollPane = null;
	private JTextArea descrArea = null;
	private JTextField genereTF = null;
	private JButton genereB = null;
	private DialogTermine dt = null;
	private JLabel calorieUnitaL = null;
	
	/**
	 * @param nomeC Il nome del cibo di cui si editano le informazioni
	 */
	public ModificaInfoCibi(Home home, String nomeC) {
		super();
		this.nomeCibo = nomeC;
		this.main = home;
		initialize();
	}
	
	public ModificaInfoCibi(Home home, Cibo cibo) {
		super();
		this.main = home;
		this.vecchioCibo = cibo;
		getGenereTF().setText(cibo.getTag().getFirst().toString());
		this.valori = cibo.getInfo().getValori();
		this.nomeCibo = cibo.getNome();
		initialize();
	}
	
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		GridBagConstraints gridBagConstraints15 = new GridBagConstraints();
		gridBagConstraints15.gridx = 2;
		gridBagConstraints15.anchor = GridBagConstraints.WEST;
		gridBagConstraints15.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints15.gridy = 4;
		calorieUnitaL = new JLabel();
		if (vecchioCibo == null || vecchioCibo.getInfo().getUnitaRiferimento() == null)
			calorieUnitaL.setText("");
		else calorieUnitaL.setText("kcal/" + vecchioCibo.getInfo().getUnitaRiferimento());
		GridBagConstraints gridBagConstraints34 = new GridBagConstraints();
		gridBagConstraints34.gridx = 2;
		gridBagConstraints34.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints34.fill = GridBagConstraints.NONE;
		gridBagConstraints34.gridy = 1;
		GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
		gridBagConstraints1.fill = GridBagConstraints.BOTH;
		gridBagConstraints1.gridy = 1;
		gridBagConstraints1.weightx = 1.0;
		gridBagConstraints1.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints1.gridx = 1;
		GridBagConstraints gridBagConstraints33 = new GridBagConstraints();
		gridBagConstraints33.fill = GridBagConstraints.BOTH;
		gridBagConstraints33.gridy = 2;
		gridBagConstraints33.weightx = 1.0;
		gridBagConstraints33.weighty = 1.0;
		gridBagConstraints33.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints33.anchor = GridBagConstraints.WEST;
		gridBagConstraints33.gridwidth = 2;
		gridBagConstraints33.gridx = 1;
		GridBagConstraints gridBagConstraints14 = new GridBagConstraints();
		gridBagConstraints14.gridx = 0;
		gridBagConstraints14.gridwidth = 3;
		gridBagConstraints14.gridwidth = 2;
		gridBagConstraints14.insets = new Insets(10, 5, 10, 5);
		gridBagConstraints14.fill = GridBagConstraints.NONE;
		gridBagConstraints14.ipadx = 0;
		gridBagConstraints14.gridheight = 1;
		gridBagConstraints14.gridy = 6;
		GridBagConstraints gridBagConstraints13 = new GridBagConstraints();
		gridBagConstraints13.gridx = 0;
		gridBagConstraints13.gridwidth = 3;
		gridBagConstraints13.gridy = 0;
		jLabel = new JLabel();
		jLabel.setText(nomeCibo);
		jLabel.setFont(new Font("Dialog", Font.BOLD, 22));
		GridBagConstraints gridBagConstraints41 = new GridBagConstraints();
		gridBagConstraints41.gridx = 1;
		gridBagConstraints41.anchor = GridBagConstraints.WEST;
		gridBagConstraints41.fill = GridBagConstraints.NONE;
		gridBagConstraints41.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints41.gridwidth = 2;
		gridBagConstraints41.gridy = 5;
		GridBagConstraints gridBagConstraints32 = new GridBagConstraints();
		gridBagConstraints32.gridx = 0;
		gridBagConstraints32.anchor = GridBagConstraints.WEST;
		gridBagConstraints32.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints32.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints32.gridy = 5;
		valoriLabel = new JLabel();
		valoriLabel.setText("Composizione chimica");
		valoriLabel.setFont(new Font("Dialog", Font.BOLD, 12));
		GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
		gridBagConstraints4.gridx = 1;
		gridBagConstraints4.gridy = 0;
		GridBagConstraints gridBagConstraints31 = new GridBagConstraints();
		gridBagConstraints31.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints31.gridy = 3;
		gridBagConstraints31.weightx = 1.0;
		gridBagConstraints31.anchor = GridBagConstraints.WEST;
		gridBagConstraints31.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints31.gridwidth = 2;
		gridBagConstraints31.gridx = 1;
		GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
		gridBagConstraints21.gridx = 0;
		gridBagConstraints21.anchor = GridBagConstraints.CENTER;
		gridBagConstraints21.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints21.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints21.gridy = 3;
		rifLabel = new JLabel();
		rifLabel.setText("Unita' di riferimento");
		rifLabel.setFont(new Font("Dialog", Font.BOLD, 12));
		GridBagConstraints gridBagConstraints12 = new GridBagConstraints();
		gridBagConstraints12.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints12.gridy = 4;
		gridBagConstraints12.weightx = 1.0;
		gridBagConstraints12.anchor = GridBagConstraints.WEST;
		gridBagConstraints12.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints12.gridwidth = 1;
		gridBagConstraints12.gridx = 1;
		GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
		gridBagConstraints3.gridx = 0;
		gridBagConstraints3.anchor = GridBagConstraints.CENTER;
		gridBagConstraints3.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints3.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints3.gridy = 4;
		calorieLabel = new JLabel();
		calorieLabel.setText("Calorie");
		calorieLabel.setFont(new Font("Dialog", Font.BOLD, 12));
		GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
		gridBagConstraints11.gridx = 0;
		gridBagConstraints11.anchor = GridBagConstraints.NORTHWEST;
		gridBagConstraints11.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints11.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints11.gridy = 2;
		descrLabel = new JLabel();
		descrLabel.setText("Descrizione *");
		descrLabel.setFont(new Font("Dialog", Font.BOLD, 12));
		GridBagConstraints gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.insets = new Insets(5, 5, 5, 5);
		gridBagConstraints.anchor = GridBagConstraints.CENTER;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.gridy = 1;
		genereLabel = new JLabel();
		genereLabel.setText("Genere *");
		genereLabel.setFont(new Font("Dialog", Font.BOLD, 12));
		this.setSize(444, 224);
		this.setLayout(new GridBagLayout());
		this.setVisible(true);
		this.setFont(new Font("Dialog", Font.BOLD, 12));
		this.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
		this.add(genereLabel, gridBagConstraints);
		this.add(descrLabel, gridBagConstraints11);
		this.add(calorieLabel, gridBagConstraints3);
		this.add(getCalorieField(), gridBagConstraints12);
		this.add(rifLabel, gridBagConstraints21);
		this.add(getUnitaBox(), gridBagConstraints31);
		this.add(valoriLabel, gridBagConstraints32);
		this.add(getValoriButton(), gridBagConstraints41);
		this.add(jLabel, gridBagConstraints13);
		this.add(getCreaButton(), gridBagConstraints14);
		this.add(getJScrollPane(), gridBagConstraints33);
		this.add(getGenereTF(), gridBagConstraints1);
		this.add(getGenereB(), gridBagConstraints34);
		this.add(calorieUnitaL, gridBagConstraints15);
		
		dt = new DialogTermine(main, TipoTermine.genere_cibo, true, true);
		getValoriButton().setEnabled(getUnitaBox().getSelectedIndex() > 0);
		getCalorieField().setEnabled(getUnitaBox().getSelectedIndex() > 0);
	}
	
	/**
	 * This method initializes calorieField
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getCalorieField() {
		if (calorieField == null) {
			calorieField = new JTextField(8);
			calorieField.setFont(new Font("Dialog", Font.PLAIN, 12));
			calorieField.setMinimumSize(new Dimension(100, 19));
			calorieField.setPreferredSize(new Dimension(100, 19));
			calorieField.setText(vecchioCibo == null ? "0" : Integer.toString(vecchioCibo.getInfo().getCalXunita()));
			calorieField.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent e) {
					if (calorieField.isEnabled()) calorieField.setText("");
				}
			});
			calorieField.addKeyListener(new NumericAdapter());
		}
		return calorieField;
	}
	
	/**
	 * This method initializes unitaBox
	 * 
	 * @return javax.swing.JComboBox
	 */
	JComboBox getUnitaBox() {
		if (unitaBox == null) {
			Set<String> unitaSet = new TreeSet<String>();
			for (Unita u : Unita.values())
				unitaSet.add(u.toString());
			unitaSet.add("Seleziona unita'..");
			unitaBox = new JComboBox(unitaSet.toArray());
			unitaBox.setFont(new Font("Dialog", Font.PLAIN, 12));
			unitaBox.setMinimumSize(new Dimension(188, 23));
			unitaBox.setPreferredSize(new Dimension(188, 23));
			if (vecchioCibo != null) {
				if (vecchioCibo.getInfo().getUnitaRiferimento() != null)
					unitaBox.setSelectedItem(vecchioCibo.getInfo().getUnitaRiferimento().toString());
				else unitaBox.setSelectedIndex(0);
			}
			unitaBox.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					getValoriButton().setEnabled(getUnitaBox().getSelectedIndex() > 0);
					getCalorieField().setEnabled(getUnitaBox().getSelectedIndex() > 0);
					if (getUnitaBox().getSelectedIndex() > 0) calorieUnitaL.setText("kcal/" + getUnitaBox().getSelectedItem());
					else if (getUnitaBox().getSelectedIndex() == 0) calorieUnitaL.setText("");
				}
			});
		}
		return unitaBox;
	}
	
	/**
	 * This method initializes valoriButton
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getValoriButton() {
		if (valoriButton == null) {
			valoriButton = new JButton();
			valoriButton.setText("Aggiungi valori");
			valoriButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
			valoriButton.setHorizontalTextPosition(SwingConstants.TRAILING);
			//valoriButton.setIcon(new ImageIcon(getClass().getResource("/icone/database-add-icon.png")));
			valoriButton.setIcon(new ImageIcon(getClass().getResource("/icone/chart-add-icon.png")));
			valoriButton.setFont(new Font("Dialog", Font.BOLD, 12));
			valoriButton.addActionListener(this);
		}
		return valoriButton;
	}
	
	/**
	 * This method initializes creaButton
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getCreaButton() {
		if (creaButton == null) {
			creaButton = new JButton();
			String action = vecchioCibo == null ? "Crea Cibo" : "Modifica cibo";
			creaButton.setText(action);
			creaButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
			creaButton.setHorizontalTextPosition(SwingConstants.TRAILING);
			creaButton.setIcon(new ImageIcon(getClass().getResource("/icone/accept-icon.png")));
			creaButton.setFont(new Font("Dialog", Font.BOLD, 12));
			creaButton.addActionListener(this);
		}
		return creaButton;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == valoriButton) {
			InserisciValori iv = new InserisciValori(main, this, valori);
			iv.setVisible(true);
		} else if (e.getSource() == creaButton) {
			do {
				String descr = descrArea.getText();
				if (descr.length() < 1) {
					JOptionPane.showMessageDialog(this, "Inserire una descrizione per il cibo", "Attenzione", JOptionPane.WARNING_MESSAGE);
					break;
				}
				String cal = calorieField.getText();
				if (unitaBox.getSelectedIndex() != 0 && (cal.length() < 1 || cal.length() > 5 || Integer.parseInt(cal) < 1)) {
					cal = "0";
				}
				Unita u = null;
				try {
					u = Unita.valueOf((String)unitaBox.getSelectedItem());
				} catch (IllegalArgumentException iae) {
//					u = UnitaPeso.valueOf((String)unitaBox.getSelectedItem());
				}
				if (getGenereTF().getText().isEmpty()) {
					JOptionPane.showMessageDialog(this, "Seleziona un genere per la classificazione del cibo", "Attenzione", JOptionPane.WARNING_MESSAGE);
					break;
				}
				Termine tCibo = new Termine(TipoTermine.genere_cibo, getGenereTF().getText());
				tag = new Termini();
				tag.add(tCibo);
				if (vecchioCibo == null) {
					Cibo c = new Cibo(nomeCibo, new InfoCibo(descr, Integer.parseInt(cal), u, valori), tag);
					try { // Teoricamente pero` non dovrebbe poter sollevare una eccezione di tipo nomegiainuso perche` lo controllo prima
						TuttiCibi.getTuttiCibi().aggiungi(c);
						JOptionPane.showMessageDialog(this, "Cibo inserito correttamente", "Cibo inserito", JOptionPane.INFORMATION_MESSAGE);
					} catch (Exception exc) {
						exc.printStackTrace();
						JOptionPane.showMessageDialog(this, "Cibo non inserito a causa di un errore", "Cibo non inserito", JOptionPane.ERROR_MESSAGE);
					}
				} else {
					try {
						vecchioCibo.modifica(new InfoCibo(descr, Integer.parseInt(cal), u, valori), tag);
						if (BaseStore.salvaModifiche(vecchioCibo))
							JOptionPane.showMessageDialog(this, "Cibo modificato correttamente", "Cibo modificato", JOptionPane.INFORMATION_MESSAGE);
					} catch (Exception exc) {
						exc.printStackTrace();
						JOptionPane.showMessageDialog(this, "Cibo non modificato a causa di un errore", "Errore", JOptionPane.ERROR_MESSAGE);
					}
				}
				main.fatto();
			} while (false);
		}
	}
	
	public void passaValori(Valori valori) {
		this.valori = valori;
	}
	
	/**
	 * This method initializes jScrollPane
	 * 
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getDescrArea());
		}
		return jScrollPane;
	}
	
	/**
	 * This method initializes descrArea
	 * 
	 * @return javax.swing.JTextArea
	 */
	private JTextArea getDescrArea() {
		if (descrArea == null) {
			descrArea = new JTextArea();
			descrArea.setLineWrap(true);
			descrArea.setWrapStyleWord(true);
			descrArea.setFont(new Font("Dialog", Font.PLAIN, 12));
			descrArea.setBorder(null);
			descrArea.setTabSize(0);
			if (vecchioCibo != null) 
				descrArea.setText(vecchioCibo.getInfo().getDescrizione());
			descrArea.addKeyListener(new java.awt.event.KeyAdapter() {
				public void keyPressed(java.awt.event.KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_TAB) {
						if (e.isShiftDown())
							getGenereTF().requestFocus();
						else getUnitaBox().requestFocus();
					}
				}
			});
		}
		return descrArea;
	}
	
	/**
	 * This method initializes genereTF
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getGenereTF() {
		if (genereTF == null) {
			genereTF = new JTextField();
			genereTF.setEditable(false);
			genereTF.setFont(new Font("Dialog", Font.PLAIN, 12));
		}
		return genereTF;
	}
	
	/**
	 * This method initializes genereB
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getGenereB() {
		if (genereB == null) {
			genereB = new JButton();
			genereB.setText("Seleziona Genere");
			genereB.setFont(new Font("Dialog", Font.BOLD, 12));
			genereB.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					dt.setVisible(true);
					if (dt.getTermine() == null)
						getGenereTF().setText("");
					else getGenereTF().setText(dt.getTermine().toString());
				}
			});
		}
		return genereB;
	}
} //  @jve:decl-index=0:visual-constraint="10,10"
